#PATH=/home/suka/rv3128/cmake-3.11.2-Linux-x86_64/bin:$PATH
#export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_NDK:$PATH

# Build helper directory
DIR_BUILD_HELPER="$(cd `dirname $BASH_SOURCE`; pwd)"

TOP=$DIR_BUILD_HELPER/..
#code directory
SOURCE_CODE_DIR=$TOP

# Prefix directory
PREFIX_PATH=$DIR_BUILD_HELPER/out

# Builder work directory
WORK_PATH=$DIR_BUILD_HELPER/work
BUILD_ORDER="opencv main save opencvcheck ffmpegcheck"


BUILD_PAR=" -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH=${PREFIX_PATH} -DCMAKE_INSTALL_PREFIX=${PREFIX_PATH} -DCMAKE_NO_SYSTEM_FROM_IMPORTED=YES"

BUILD_opencv_OPTION="-DOPENCV_EXTRA_MODULES_PATH='$TOP/opencv_contrib/modules/' -DBUILD_ANDROID_EXAMPLES=OFF -DBUILD_ANDROID_PROJECTS=OFF -DBUILD_JAVA=OFF" 


############## make dir ###################

for var in ${BUILD_ORDER}
do
	if [ ! -d ${WORK_PATH}/${var} ];then
		mkdir -p ${WORK_PATH}/${var}
	fi
done


exe_clean(){
	cd ${WORK_PATH}/$1

	make clean 
	ret=$?
	if [ ${ret} != 0 ]; then
		echo "make clean ${SOURCE_CODE_DIR}/$1 failure. errorno ${ret}"
		exit -1
	fi
}
exe_make(){
	cd ${WORK_PATH}/$1

	make -j4 && make install  
	ret=$?
	if [ ${ret} != 0 ]; then
		echo "make ${SOURCE_CODE_DIR}/$1 failure. errorno ${ret}"
		exit -1
	fi
}
exe_cmake(){
	cd ${WORK_PATH}/$1
	
	eval BUILD_SELF_OPTION='${'"BUILD_$1_OPTION"'}'

	echo "cmake ${SOURCE_CODE_DIR}/$1 ${BUILD_PAR} ${BUILD_OTHER_OPTION} ${BUILD_SELF_OPTION}"

	cmake ${SOURCE_CODE_DIR}/$1 ${BUILD_PAR} ${BUILD_OTHER_OPTION} ${BUILD_SELF_OPTION}

	ret=$?
	if [ ${ret} != 0 ]; then
		echo "cmake ${SOURCE_CODE_DIR}/$1 failure. errorno ${ret}"
		exit -1
	fi
	exe_make $1
}
help(){
	submodules_str=`echo ${BUILD_ORDER} | sed "s\ \ | \g" `
	echo "no support $var, only support parameter "
	echo "{cmake | make | clean} [$submodules_str]"
	exit -1
}
check_make(){
	if [ $1 = "YES" ]; then
		exe_make $2
		return 0
	fi
	return -1
}
check_cmake(){
	if [ $1 = "YES" ]; then
		exe_cmake $2
		return 0
	fi
	return -1
}

exe_command(){
	if [ $4x = "YES"x ];then
		exe_clean $3
		return 0
	fi
	check_cmake $1 $3
	if [ $? != 0 ]; then
		check_make $2 $3
		
		if [ $? = 0 ]; then
			return 0
		fi
		help
		return -1
	fi
	return 0
}

############## parameter ###################
CMAKE="NO"
MAKE="NO"
SINGLE_EXE="NO"
CLEAN="NO"
if [  "$*"x = x ]; then
	help
	exit -1
fi

for var in $* 
do
	if [ $var = "cmake" ]; then
		CMAKE="YES"
	elif [ $var = "make" ]; then
		MAKE="YES"
	elif [ $var = "clean" ]; then
		CLEAN="YES"
	elif [[ ${BUILD_ORDER} =~ ${var} ]]; then
		exe_command $CMAKE $MAKE $var $CLEAN
		SINGLE_EXE="YES"
	else 
	  	help
		exit -1
	fi
done





############## exe cmake ###################

if [ "$SINGLE_EXE"x != "YES"x ];then
	for var in ${BUILD_ORDER}
	do
		exe_command $CMAKE $MAKE $var $CLEAN
		 
	done
fi


